<template>
  <div class="kitchen-dashboard">
    <div class="dashboard-header">
      <h2>待处理订单 ({{ pendingOrders.length }})</h2>
      <div class="controls">
        <button @click="toggleAudio" class="audio-btn">
          {{ isAudioEnabled ? "🔊 关闭提示音" : "🔈 开启提示音" }}
        </button>
      </div>
    </div>

    <div class="orders-grid">
      <OrderItem
        v-for="order in pendingOrders"
        :key="order.id"
        :order="order"
        @complete-order="completeOrder"
      />
    </div>
  </div>
</template>

<script>
import OrderItem from "./OrderItem.vue";

export default {
  name: "KitchenDashboard",
  components: {
    OrderItem,
  },
  data() {
    return {
      pendingOrders: [],
      isAudioEnabled: true,
      newOrderAudio: null,
    };
  },
  methods: {
    completeOrder(order) {
      const index = this.pendingOrders.findIndex((o) => o.id === order.id);
      if (index > -1) {
        order.status = "completed";
        order.completedTime = new Date().toLocaleTimeString();
        this.pendingOrders.splice(index, 1);
        this.$emit("order-completed", order);
      }
    },
    receiveNewOrder(order) {
      order.status = "pending";
      order.time = new Date().toLocaleTimeString();
      this.pendingOrders.push(order);
      if (this.isAudioEnabled) {
        this.playNewOrderAudio();
      }
    },
    playNewOrderAudio() {
      if (this.newOrderAudio) {
        this.newOrderAudio.click(); // 【主要代码 - 解决报错】先模拟与页面进行交互，防止报错
        this.newOrderAudio.play();
      }
    },
    toggleAudio() {
      this.isAudioEnabled = !this.isAudioEnabled;
    },
    initAudio() {
      this.newOrderAudio = new Audio("/audio/new-order.mp3");
    },
  },
  mounted() {
    this.initAudio();
  },
};
</script>

<style scoped>
.kitchen-dashboard {
  padding: 20px;
}

.dashboard-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.controls {
  display: flex;
  gap: 10px;
}

.audio-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  background-color: #2196f3;
  color: white;
  cursor: pointer;
}

.orders-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}
</style>
